<?php

namespace PolarisbackEndFrameRe\api\log;

class Logger
{
    const DEBUG = 100;
    const INFO = 200;
    const WARNING = 300;
    const ERROR = 400;

    private $logFile;
    private $logLevel;

    public function __construct($logFile, $logLevel = self::DEBUG)
    {
        $this->logFile = $logFile;
        $this->logLevel = $logLevel;
    }

    public function debug($message)
    {
        $this->log(self::DEBUG, $message);
    }

    public function info($message)
    {
        $this->log(self::INFO, $message);
    }

    public function warning($message)
    {
        $this->log(self::WARNING, $message);
    }

    public function error($message)
    {
        $this->log(self::ERROR, $message);
    }

    private function log($level, $message)
    {
        if ($this->shouldLog($level)) {
            $timestamp = date('Y-m-d H:i:s');
            $levelName = $this->getLevelName($level);
            $logMessage = sprintf("[%s] [%s] %s\n", $timestamp, $levelName, $message);
            file_put_contents($this->logFile, $logMessage, FILE_APPEND);
        }
    }

    private function shouldLog($level)
    {
        return $level >= $this->logLevel;
    }

    private function getLevelName($level)
    {
        switch ($level) {
            case self::DEBUG:
                return 'DEBUG';
            case self::INFO:
                return 'INFO';
            case self::WARNING:
                return 'WARNING';
            case self::ERROR:
                return 'ERROR';
            default:
                return 'UNKNOWN';
        }
    }
}